package Options::UserSync::API::AddressFieldsConverter;
use strict;

use Options::UserSync::API::CountriesConverter;
use DE_EPAGES::Object::API::Object::Object qw(insertChild existsChild);
use DE_EPAGES::Core::API::Log qw (LogDebug GetLog);

use DE_EPAGES::Database::API::Connection qw( GetCurrentDBHandle );
use DE_EPAGES::Object::API::Factory qw( LoadObject ExistsObjectByPath LoadObjectByPath Transaction DeleteObject LoadClassByAlias);
use DE_EPAGES::Shop::API::Table::ShopCountry qw (GetInfoShopCountriesByShopID InsertShopCountry ExistsShopCountry DeleteShopCountry);
use DE_EPAGES::Object::API::Language qw (GetPKeyLanguageByCode);
use DE_EPAGES::Database::API::Connection qw( RunOnStore );
use DE_EPAGES::Core::API::Script qw( RunScript );
use DE_EPAGES::Product::API::Product qw (SubProductFolder JoinVariationValues GetInfoSubProductsBySuperProductID);
use DE_EPAGES::Order::API::Basket qw(GetExistingBasket);
use DE_EPAGES::Product::API::Basket qw( AddProducts );
use DE_EPAGES::Catalog::API::Catalog qw (AssignProductToCategory);
use DE_EPAGES::Presentation::API::PageCache qw (InvalidatePageCache);
use DE_EPAGES::Core::API::Error qw( Error ExistsError GetError );
use DE_EPAGES::Core::API::Warning qw( Warning );
use DE_EPAGES::WebInterface::API::MessageCenter qw( SynchronizeCache );
use DE_EPAGES::Presentation::API::User qw( CreateUser ExistsUser GetUserFolder );
use DE_EPAGES::Customer::API::Shop qw( InsertUserForCustomer InsertCustomerForUser );


use Data::Dumper;

sub new
{
    my $class = $_[0];
    my $self;
#    $self->{epagesAddress} = $_[1];
#    $self->{optionsCustomer} = $_[2];
#    $self->{addressType} = $_[3];
    my %FieldsAssignment = (    
		    #EPAGES:							#OPTIONS:
          	#	'Alias'							=> 'CustomerNumber',
          		'Title' 						=> 'TitleCode',
          		'Salutation' 						=> 'Salutation',
          		'FirstName' 						=> 'FirstName',
          		'LastName' 						=> 'Surname',
          		'AddressExtension' 					=> 'Address1',          	
          		'Street' 						=> 'Address2',
          		'Street2'						=> 'Address3',
          		'City' 							=> 'Town',
          		'CountryID' 						=> 'Country',
          		'State' 						=> 'County',
          		'Zipcode'						=> 'Postcode',
          		'Phone' 						=> 'DayPhone',
          		'EMail' 						=> 'Email',
                'Company'                       => 'AddressRef1',
                'Department'                    => 'AddressRef2',     		
		);	
    $self->{_fieldsAssignment} = \%FieldsAssignment;
#    if($_[3] eq "shipping") {
#	$self->{_fieldsAssignment}->{AddressNumber} = 'AddressNumber';
#    }
    bless $self, $class;
#    $self->updateOptionsAddress();
    return $self;
}

sub convertToOptions {
    my $self = shift;
    $self->{epagesAddress} = shift;
    $self->{optionsCustomer} = shift;
    $self->{addressType} = shift;
    if($self->{addressType} eq "shipping") {
	$self->{_fieldsAssignment}->{AddressNumber} = 'AddressNumber';
    }
    $self->updateOptionsAddress();
}

sub convertFromOptionsBillingAddress {
    my $self = shift;
    my $epagesBillingAddress = shift;
    my $optionsCustomer = shift;
    my $AddressRecord = {};
    #This MF prevents hooks clashing.
    $AddressRecord->{BFLastSyncTimestamp} = time;
    while ( my ($k, $v) = each %{$self->{_fieldsAssignment}} ) {
	if ($k eq "CountryID") {
	    $AddressRecord->{$k} = $self->covnertCountryFromOptions($optionsCustomer->{$v}); 
	} else {
	    $AddressRecord->{$k} = $optionsCustomer->{$v};
	}
    }
    $epagesBillingAddress->set($AddressRecord);
   # GetLog->error("epages update hash CustomerBillingAddresses: " . Dumper(\%AddressRecord));
}

sub convertFromOptionsShippingAddress {
    my $self = shift;
    my $epagesAddresses = shift;
    my $optionsCustomerAddresses = shift;
    my $userOBJ = shift;
    my $addressesOBJID = shift;
    $self->{_fieldsAssignment}->{AddressNumber} = 'AddressNumber';
    my $epagesShippingAddressesNumber = 0;
    my $optionsShippingAddressesNumber = 0;


    foreach (@$epagesAddresses) {
#This will never occur: we will always update all addresses by deleting and importing
    	if ($_->get('Alias') =~ m/ShippingAddress/) {
    	   $epagesShippingAddressesNumber++; 
    	}
    }
    $optionsShippingAddressesNumber = scalar(@$optionsCustomerAddresses);
    #########################################   
    if ($epagesShippingAddressesNumber == $optionsShippingAddressesNumber) {
	#just update the addresses
	my $recordIND = 0;
    	foreach (@$epagesAddresses) {
    	    if ($_->get('Alias') =~ m/ShippingAddress/) {
        		my $AddressRecord = {};
        		#This MF prevents hooks clashing.
        		$AddressRecord->{BFLastSyncTimestamp} = time;
        		while ( my ($k, $v) = each %{$self->{_fieldsAssignment}}) {
        		GetLog->debug($k . " - " . $v);
        		    if ($k eq "CountryID") {
        			 $AddressRecord->{$k} = $self->covnertCountryFromOptions($optionsCustomerAddresses->[$recordIND]->{$v});
        		    } else {
        			 $AddressRecord->{$k} = $optionsCustomerAddresses->[$recordIND]->{$v};
        		    }  
        		}
        		GetLog->debug("epages update hash CustomerShippingAddresses: " . Dumper($AddressRecord));
        		$_->set($AddressRecord);
        		$recordIND++;
    	    }
    	    
    	}	
    } elsif ($epagesShippingAddressesNumber > $optionsShippingAddressesNumber) {
	#delete address from epages - not supported yet
    } elsif ($epagesShippingAddressesNumber < $optionsShippingAddressesNumber) {
    #insert new address from options
           
        foreach (@$optionsCustomerAddresses) {
            
        my $optionsAddressNumber = $_->{'AddressNumber'};
        my $AddressRecord = {};
        
        $AddressRecord->{BFLastSyncTimestamp} = time; 
        while ( my ($k, $v) = each %{$self->{_fieldsAssignment}}) {    
                    if ($k eq "CountryID") {
                     $AddressRecord->{$k} = $self->covnertCountryFromOptions($_->{$v});
                    } else {
                     $AddressRecord->{$k} = $_->{$v};
                    }  
        }
        $optionsAddressNumber++;
        my $Folder  = $userOBJ->get('Addresses');
        my $Folderqq = LoadObject(39830);
 GetLog->debug($Folderqq->get('Path'));       
        my $NewAlias = "Address" . $optionsAddressNumber;
        
        $AddressRecord->{'Alias'} = $NewAlias;
        
GetLog->debug("THIS ADDRES IS ADDED: $NewAlias :\n" . Dumper($AddressRecord));         

        my $newAddressTBC;

        if ( not $userOBJ->folder('Addresses')->existsChild( $NewAlias ) ) {
GetLog->debug("THIS ADDRES IS ADDED: $NewAlias :\n" . Dumper($AddressRecord)); 
	     $userOBJ->folder('Addresses')->insertChild('Address', $AddressRecord);    
        } else {
GetLog->debug("THIS ADDRES IS REMOVED AND ADDED: $NewAlias :\n" . Dumper($AddressRecord));                         
             $newAddressTBC = $userOBJ->folder('Addresses')->child($NewAlias)->get('ObjectID');
             DeleteObject($newAddressTBC);
             $userOBJ->folder('Addresses')->insertChild('Address', $AddressRecord);
        }       
        }

    }
}

sub updateOptionsAddress {
    my $self = shift;
    print Dumper($self);
    $self->selectCurrentShippingAddress;
    #if ($self->selectCurrentShippingAddress) {
        if ($self->{addressType} eq "billing") {
        	while( my ($k, $v) = each %{$self->{_fieldsAssignment}} ) {
        	    if ($k eq "CountryID") {
            	    my $returnedISO = $self->covnertCountryForOptions($self->{epagesAddress}->get($k));
            	    GetLog->debug("RETURNEEEED ISO:::::::::" . $returnedISO);   
            		$self->{optionsCustomer}->{$v} = $returnedISO;
        	    } else {
        		$self->{optionsCustomer}->{$v} = $self->{epagesAddress}->get($k);
        	    }
        	}
        } elsif ($self->{addressType} eq "shipping") {
        	#in case when we have more than one shipping address
        	$self->selectCurrentShippingAddress;
        	while( my ($k, $v) = each %{$self->{_fieldsAssignment}} ) {
            	    if ($k eq "CountryID") {
                	    my $returnedISO = $self->covnertCountryForOptions($self->{epagesAddress}->get($k));
                	    GetLog->debug("RETURNEEEED ISO:::::::::" . $returnedISO);    
                		$self->{optionsCustomer}->{AdditionalAddresses}->{CustomerAdditionalAddress}->{$v} = $returnedISO;
            	    } else {
            		$self->{optionsCustomer}->{AdditionalAddresses}->{CustomerAdditionalAddress}->{$v} = $self->{epagesAddress}->get($k);			    
            	    }
        	}  
        }
    #}
}

sub covnertCountryFromOptions {
    my $self = shift;
    my $name = shift;
  #  my $CountryConverter = new Options::UserSync::API::CountriesConverter();
   # return $CountryConverter->getCountryISOByBFName($name);
    return $name;
}

sub covnertCountryForOptions {
    my $self = shift;
    my $iso = shift;
    GetLog->debug("OOOORYGINAL ISO:::::::::" . $iso);   
    my $x = length $iso;
    if ($x == 2) {
        return "0" . $iso;
    } elsif ($x == 1) {
        return "00" . $iso;       
    } else {
        return $iso;  
    }
  #  my $CountryConverter = new Options::UserSync::API::CountriesConverter();
 #   return "" . $iso;
   # return $CountryConverter->getBFNameByCountryISO($iso);
}

sub selectCurrentShippingAddress {
    my $self = shift;
    GetLog->debug("QQQQQQQQ CustomerBillingAddresses: " . Dumper($self->{optionsCustomer}));
    if ($self->{optionsCustomer} ne "") {
        if (defined($self->{optionsCustomer}->{AdditionalAddresses})) {
            if (ref($self->{optionsCustomer}->{AdditionalAddresses}) eq "HASH") {
                if (ref($self->{optionsCustomer}->{AdditionalAddresses}->{CustomerAdditionalAddress}) eq "ARRAY") {
                	#remove all addresses and leave just the proper one
                	foreach (@{$self->{optionsCustomer}->{AdditionalAddresses}->{CustomerAdditionalAddress}}) {
                	    if ($_->{AddressNumber} == $self->{epagesAddress}->get('AddressNumber')) {
                		   $self->{selectedCurrentAddress} = $_;
                    	}
                	}
                	delete($self->{optionsCustomer}->{AdditionalAddresses}->{CustomerAdditionalAddress});
                	if(defined($self->{selectedCurrentAddress})) {
                	    $self->{optionsCustomer}->{AdditionalAddresses}->{CustomerAdditionalAddress} = $self->{selectedCurrentAddress};
                	}
                   return 1;                	
                } elsif (ref($self->{optionsCustomer}->{AdditionalAddresses}->{CustomerAdditionalAddress}) eq "HASH") {
            	   delete($self->{optionsCustomer}->{AdditionalAddresses}->{CustomerAdditionalAddress});
            	   return 1;
                }
            }
        }
    }
    return 0;
}

sub getOptionsByEpagesFN {
    my $self = shift;
    my $name = shift;
    return $self->{_fieldsAssignment}->{$name};
}

sub getEpagesByOptionsFN {
    my $self = shift;
    my $name = shift;
    while( my ($k, $v) = each %{$self->{_fieldsAssignment}} ) {
	if($v eq $name) {
	   return $k; 
	}
    }
}

1;
